<?php

namespace Blockgolde\HyperfBusinessWrapper\Utils;

class NetworkUtil
{
    /**
     * 获取IP
     * @param \Hyperf\HttpServer\Contract\RequestInterface $request
     * @return string
     */
    function getIp(Hyperf\HttpServer\Contract\RequestInterface $request):string
    {
        $res = $request->getHeaders();
        if (isset($res['x-real-ip'])) {
            return current($res['x-real-ip']);
        } elseif (isset($res['x-forwarded-for'])) {
            return current($res['x-forwarded-for']);
        } elseif (isset($res['http_x_forwarded_for'])) {
            //部分CDN会获取多层代理IP，所以转成数组取第一个值
            $arr = explode(',', $res['http_x_forwarded_for']);
            return $arr[0];
        } else {
            $res = $request->getServerParams();
            return $res['remote_addr'];
        }
    }
}